package com.example.getfromservice.Activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import com.example.getfromservice.R;
import com.example.getfromservice.Book.Book;
import com.example.getfromservice.Book.BookDAO;
import com.example.getfromservice.Book.DataHandlerBook;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

public class FourthActivity extends Activity {
	
	
	
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	private Book book;
	private LongRunningAccept longRunningaccept = null;
	private boolean mDone;
	private Bundle extras;
	private int[] info_from_main_activity ;
	private Bitmap tmpbmp = null;
	private BookDAO bookdatasource;
	
	
	//*********************************************** ONCREATE ****************************************
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
      
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fourth);
        
        bookdatasource = new BookDAO(this);
		bookdatasource.open();
		
        extras = getIntent().getExtras();
        info_from_main_activity = extras.getIntArray("Info");
        

       if( info_from_main_activity[2] != 0 )
	        {	            
	    	   	inputdata( info_from_main_activity[0] , info_from_main_activity[1] );      
	        	    
	        }
       
    }
    
  //*********************************************** ONPAUSE ****************************************

    @Override
    protected void onPause() {
      bookdatasource.close();
      super.onPause();
    }
    
  //*********************************************** ONRESUME ****************************************
    
    @Override
    protected void onResume() {
      bookdatasource.open();
      super.onResume();
    }
    
  //*********************************************** ISONLINE ****************************************
    
    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
       
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
           
        	return true;
        }
        
        return false;
    }

  //*********************************************** INPUTDATA ****************************************  
    
    // Info - { category_id, book_id , action }
    private void inputdata(int catId ,int bookId) {
		
    	EditText bookisbn = (EditText) findViewById(R.id.eTisbn);
    	EditText booktitle = (EditText) findViewById(R.id.eTtitle);
    	EditText bookauthor = (EditText) findViewById(R.id.eTauthor);
    	
    	ImageView imagex = (ImageView) findViewById(R.id.imageView14);
    	book = new Book();	
    	
    	if( !isOnline() ) 
	    	{
	    			book = bookdatasource.selectBookfromDB(bookId);
	    		 
	    			bookisbn.setText(book.getISBN());
					booktitle.setText(book.getTitle());
					bookauthor.setText(book.getAuthor());
					
	    		
				
					if(book.getImage() != null)
						{
							imagex.setImageBitmap(book.getImage());
						}	
	    		
	    	}
    	else if ( isOnline() )
    		{
    		
		    		DataHandlerBook xmlparser = new DataHandlerBook();
		    		
		    		List<Book> books_list = new ArrayList<Book>();  
			    	
		    		books_list = xmlparser.getAllBooks(catId+"");
			    	  
		
					for (Book bok : books_list) {
						
						if( bok.getID() == bookId )
							{
								book = bok;
								break;
							}
					}
					
					bookisbn.setText(book.getISBN());
					booktitle.setText(book.getTitle());
					bookauthor.setText(book.getAuthor());
					
		    		
					
					if(book.getImage() != null)
						{
							imagex.setImageBitmap(book.getImage());
						}
					
    		}
		
	}
 
  //*********************************************** MENU ****************************************
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_fourth, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
 
        switch (item.getItemId())
        {
	        case R.id.menu_photo: 
						        {
						        	// create Intent to take a picture and return control to the calling application
								    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
									
								    // start the image capture Intent
								    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
						        }
	        return true;
        }
        
        return false;
    }
    
    
    
    public void onClick( View view )
    {
	    switch(view.getId())
	    {
	    
			case R.id.okbook : 
			{
				
				
				boolean needToCreate = false;
				
	 			if (longRunningaccept == null) {
	 			      needToCreate=true;
	 			} else {
	 				if (longRunningaccept.isDone()) {
	 					needToCreate=true;
	
	 					longRunningaccept = null;
	 				}
	 			}
	 			if (needToCreate) {
	 				longRunningaccept = new LongRunningAccept();
	 				
	 				int id = info_from_main_activity[0];
	 				
	 				if( info_from_main_activity[2]==0)
	 				{
	 					longRunningaccept.execute(id,0);
	 				}
	 				else
	 				{
	 				
	 					longRunningaccept.execute(id,book.getID());	
	 				}
	 			}
				
			}
			break;
	
	    }
    
    }
    
  //*********************************************** SAVEBMP ****************************************
    
    private void saveBmp(String filename)
    {
    	try{
		    	String path = Environment.getExternalStorageDirectory().toString();
		        OutputStream fOut = null;
		        File file = new File(path, ""+filename+".jpg");
		        fOut = new FileOutputStream(file);
		
		        tmpbmp.compress(Bitmap.CompressFormat.JPEG, 50, fOut);
		        
		        fOut.flush();
		        fOut.close();
  
        }catch(Exception e){e.printStackTrace();}
    }
    
  //*********************************************** RESULTCAMERA ****************************************
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		 super.onActivityResult(requestCode, resultCode, data);

	 
		
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) 
			{

		            try{
		            		ImageView my = (ImageView) findViewById(R.id.imageView14);
		            		Bitmap bmp = (Bitmap) data.getExtras().get("data");
		            		my.setImageBitmap(bmp);
		            		
		            	
		            }catch(Exception e)
		            	{
		            		e.printStackTrace();
		            	}
      
	        } 
	    }

	//*********************************************** ACCEPT ****************************************    	
	
    private class LongRunningAccept extends AsyncTask<Integer, Void, Integer> {

		boolean isDone() { return mDone; }

		@Override
		protected Integer doInBackground(Integer... params) {

			EditText booktitle = (EditText) findViewById(R.id.eTtitle);
			EditText bookisbn = (EditText) findViewById(R.id.eTisbn);
			EditText bookauthor = (EditText) findViewById(R.id.eTauthor);
			
			ImageView bookimage = (ImageView) findViewById(R.id.imageView14);
			book = new Book();
			String xml = null;
			
			bookimage.buildDrawingCache();
			tmpbmp = bookimage.getDrawingCache();
			saveBmp(info_from_main_activity[1]+"");
			HttpClient httpclient = new DefaultHttpClient();
			
			try{
					// 0 - new ; 1 - update
					if( isOnline() && info_from_main_activity[2] == 0 )
						{
						
								ByteArrayOutputStream stream = new ByteArrayOutputStream();
								tmpbmp.compress(Bitmap.CompressFormat.JPEG, 85, stream);
								byte[] b = stream.toByteArray();
								String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
							
								int last = info_from_main_activity[3]+1;
							
					    	    HttpPost httppost = new HttpPost("http://10.0.2.2:8020/categoryservice/category/"+params[0]+"/book/");
						
					    	    xml = "<Book><author>"+bookauthor.getText()+"</author><bookISBNnumber>"+bookisbn.getText()+"</bookISBNnumber><bookId>"+last+"</bookId><bookName>"+booktitle.getText()+"</bookName><image>"+encodedImage+"</image></Book>";
					    	    
					    	    httppost.addHeader("Content-Type", "application/xml");
					    	    
					    	    StringEntity se = new StringEntity(xml,HTTP.UTF_8);
					    	    httppost.setEntity(se);  
					    	    
					    	    se.setContentType("application/xml");
					    	    
					    	    // Execute HTTP Post Request
					    	    HttpResponse response = httpclient.execute(httppost);
					    	    Log.i("Respones",response.toString());
				    	   
						}
					else if( isOnline() && info_from_main_activity[2] == 1 )
						{
					
								bookimage.buildDrawingCache();
								Bitmap bmap = bookimage.getDrawingCache();
				
													    	    
							    HttpDelete httpdelete = new HttpDelete("http://10.0.2.2:8020/categoryservice/category/"+params[0]+"/"+params[1]);
							    	    
							    HttpResponse response = httpclient.execute(httpdelete);  
							    Log.i("Respones",response.toString());
							    	    
								ByteArrayOutputStream stream = new ByteArrayOutputStream();
								bmap.compress(Bitmap.CompressFormat.JPEG, 85, stream);
								byte[] b = stream.toByteArray();
								String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
									   
								HttpPost httppost = new HttpPost("http://10.0.2.2:8020/categoryservice/category/"+params[0]+"/book/");
										
							    xml = "<Book><author>"+bookauthor.getText()+"</author><bookISBNnumber>"+bookisbn.getText()+"</bookISBNnumber><bookId>"+info_from_main_activity[1]+"</bookId><bookName>"+booktitle.getText()+"</bookName><image>"+encodedImage+"</image></Book>";
							    	 
								httppost.addHeader("Content-Type", "application/xml");
								    	    
								StringEntity se = new StringEntity(xml,HTTP.UTF_8);
								httppost.setEntity(se);  
								    	    
								se.setContentType("application/xml");
								    	    
								// Execute HTTP Post Request
								HttpResponse responses = httpclient.execute(httppost);
								Log.i("Respones",responses.toString());
						    						
						}
					else if( !isOnline() && info_from_main_activity[2] == 0 )
						{
								book.setAuthor(bookauthor.getText().toString());
								book.setCategory_id(params[0].toString());
								book.setChanges(2);
								int last = bookdatasource.getLastInsertId();
								last+=1;
								book.setID(last);
								book.setISBN(bookisbn.getText().toString());
								book.setName(booktitle.getText().toString());
								
					
								saveBmp(book.getID()+"");
					
								bookdatasource.addBook(params[0].toString(), book);
					
						}
					else if( !isOnline() && info_from_main_activity[2] == 1 )
						{
								
								book.setAuthor(bookauthor.getText().toString());
								book.setCategory_id(params[0].toString());
								book.setChanges(1);
								book.setID(info_from_main_activity[1]);
								book.setISBN(bookisbn.getText().toString());
								book.setName(booktitle.getText().toString());
					
					
								saveBmp(book.getID()+"");
					
								bookdatasource.updateBookinDB(book);
						}
			   
			}catch(Exception pce) 
				{ 
    
					Log.e("AndroidTestsActivity", "PCE "+pce.getMessage()); 
    	
				}
	
		return 1;
		}

		protected void onPostExecute(Integer results) {
			if (results == 1) {

					bookdatasource.close();
					finish();
			     		
			}
	
		}

	}
}
